package com.ruoyi.collect.pressure.manager;


import com.ruoyi.collect.pressure.model.CollectorPressureDto;
import com.ruoyi.collect.pressure.model.FileDto;
import com.ruoyi.collect.pressure.service.CollectParser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SnowflakeIdUtils;
import com.ruoyi.system.domain.dto.GradedAlarmDto;
import org.springframework.beans.BeanUtils;
import com.ruoyi.pressure.domain.*;
import com.ruoyi.tube.domain.Sgcddy;
import com.ruoyi.tube.domain.Sgcdss;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
public class PressureParser extends CollectParser {

    SnowflakeIdUtils snowflakeIdUtils = new SnowflakeIdUtils(5, 8);


    public PressureParser(CollectorPressureDto mapperDto, final Charset charset) {
        mapper = mapperDto;
        this.charset = charset;
    }

    @Override
    public void parse(final List<FileDto> files) {
        Stream.of((Consumer<List<FileDto>>)
                this::analyzeDblcFile,
                this::analyzeMgylFile,
                this::analyzeLcssFile,
                this::analyzeMgssFile,
                this::analyzeLcycFile,
                this::analyzeMgycFile
        ).parallel().forEach(a -> tryAnalyze(a, files));

    }

    protected String getFileNameRegex(final String type) {
        return String.join("", "(\\d+)_", type, "_(\\d{14}).txt");
    }

    protected String getDatum(String[] data, int index) {
        if (data == null || data.length <= index) {
            log.warn("null[{}]: {}", data, index);
            return null;
        }
        String datum = data[index];
        if (!StringUtils.hasText(datum)) {
            log.warn("empty[{}]: {}", data, index);
        }
        return datum.trim();
    }

    protected BigDecimal getDecimal(String[] data, int index) {
        Logger log = LoggerFactory.getLogger(this.getClass());
        if (data == null || data.length <= index || data[index] == null) {
            log.warn("Invalid data or index: data = {}, index = {}", data, index);
            return null;
        }

        String datum = data[index].trim();
        if (!StringUtils.hasText(datum)) {
            log.warn("Empty value at index {}: data = {}", index, data);
            return null;
        }

        try {
            // 将字符串转换为 Decimal
            BigDecimal value = new BigDecimal(datum);
            return value;
        } catch (NumberFormatException e) {
            log.warn("Failed to convert value at index {}: data = {}", index, data, e);
            return null;
        }
    }
    private String getType(final String type) {
        if (type == null) {
            return "其它类型";
        }
        switch (type) {
            case "8001":
                return "CH4";
            case "8002":
                return "CO";
            case "8003":
                return "O2";
            case "8004":
                return "C2H2";
            case "8005":
                return "NO";
            case "8006":
                return "CO2";
            case "8007":
                return "C2H4";
            case "8008":
                return "C2H6";
            case "8009":
                return "N2";
        }
        return "其它类型";
    }
    private String getStatus(final String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "00000000":
                return "正常";
            case "00000001":
                return "超限报警";
            case "00000010":
                return "标校";
            case "00000100":
                return "超量程";
        }
        return "";
    }

    private String getMeasurementPointStatus(final String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "0":
                return "00000000";
            case "1":
                return "00000001";
            case "2":
                return "00000010";
            case "4":
                return "00000100";
            case "8":
                return "00001000";
            case "16":
                return "00010000";
            case "32":
                return "00100000";
            case "64":
                return "01000000";
            case "128":
                return "10000000";
        }
//        switch (status) {
//            case "0":
//                return "正常";
//            case "1":
//                return "报警";
//            case "2":
//                return "负漂";
//            case "4":
//                return "离线";
//            case "8":
//                return "超量程";
//            case "16":
//                return "分站故障";
//            case "32":
//                return "不巡检";
//            case "64":
//                return "暂停";
//            case "128":
//                return "传感器故 障";
//        }
        return "";
    }

    private String getSystemCode(final String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "80":
                return "束管监测系统";
        }
        return "";
    }

    private String getValueType(final String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "MN":
                return "模拟量";
        }
        return "";
    }

    private String getSensorType(final String sensorType){
        if (sensorType == null) {
            return "";
        }
        switch (sensorType) {
            case "1101":
                return "工作面支架阻力";
            case "1201":
                return "钻孔应力";
            case "1202":
                return "围岩应力";
            case "1301":
                return "锚杆应力";
            case "1302":
                return "锚索应力";
            case "1401":
                return "顶板离层位移";
            case "1501":
                return "巷道位移";
            case "1601":
                return "微震(电动式)";
            case "1602":
                return "微震(电容式)";
            case "1603":
                return "微震(伺服式)";
            case "1604":
                return "微震(电阻式)";
            case "1605":
                return "微震(电涡流式)";
            case "1606":
                return "微震(压电式)";
            case "1607":
                return "微震(磁敏式)";
            case "1608":
                return "微震(光纤式)";
            case "1609":
                return "微震(其他)";
            case "1701":
                return "地音(电动式)";
            case "1702":
                return "地音(电容式)";
            case "1703":
                return "地音(伺服式)";
            case "1704":
                return "地音(电阻式)";
            case "1705":
                return "地音(电涡流式)";
            case "1706":
                return "地音(压电式)";
            case "1707":
                return "地音(磁敏式)";
            case "1708":
                return "地音(光纤式)";
            case "1709":
                return "地音(其他)";
            case "1801":
                return "电磁强度";
            case "1802":
                return "电磁脉冲";
        }
        return "";
    }

    //巷道表面位移测点基本信息数据项说明
//    private void analyzeBmwyFile(List<FileDto> FileDtos) {
//        List<FileDto> FileDto = FileDtos.stream()
//                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
//                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
//                .collect(Collectors.toList());
//
//        Stream.of((Consumer<List<com.ruoyi.collect.pressure.model.FileDto>>) this::analyzeKyBmwy).parallel().forEach(a -> tryAnalyze(a, FileDto));
//    }
//
//    protected void analyzeKyBmwy(final List<FileDto> fileInfos) {
//        analyze("HDWY",fileInfos,this::analyzeKyBmwy);
//    }
//
//    private void analyzeKyBmwy(final List<String> matches, final String content, FileDto fileInfo) {
//        long begin = System.currentTimeMillis();
//        int count = 0;
//        String[] lines = content.split("\\|\\|");
//        for (String line : lines) {
//            try {
//                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
//                if (parts.length < 2) {
//                    // 如果字段数量不足，跳过该行
//                    log.warn("Invalid line: {}", line);
//                    continue;
//                }
//                for (int i = 1; i < parts.length; i++) {
//                    // 第一个部分处理
//                    String[] mines = parts[0].split(";");
//                    String mineCode = getDatum(mines, 0);
//
//                    // 第二个部分使用 ';' 分割
//                    String[] data = parts[i].split(";");
//
//                    if (data.length < 9) {
//                        log.info("data_invalid: [{}]", line);
//                        continue;
//                    }
//                    long start = System.currentTimeMillis();
//                    String measurementPointCode = getDatum(data, 0);
//                    String monitoringArea = getDatum(data, 1);
//                    String sensorType = getSensorType(getDatum(data, 2));
//                    String laneName = getDatum(data, 3);
//                    String sensorLocation = getDatum(data, 4);
//                    Date installTime = new SimpleDateFormat("yyyy-MM-dd").parse(getDatum(data, 5));
//                    BigDecimal sensorCoordinateX = getDecimal(data, 6);
//                    BigDecimal sensorCoordinateY = getDecimal(data, 7);
//                    BigDecimal sensorCoordinateZ = getDecimal(data, 8);
//
//
//                    KyLaneBmwy kyLaneBmwy = new KyLaneBmwy();
//                    kyLaneBmwy.setLaneBmwyId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
//                    kyLaneBmwy.setMeasurementPointCode(measurementPointCode);
//                    kyLaneBmwy.setMonitoringArea(monitoringArea);
//                    kyLaneBmwy.setSensorType(sensorType);
//                    kyLaneBmwy.setLaneName(laneName);
//                    kyLaneBmwy.setSensorLocation(sensorLocation);
//                    kyLaneBmwy.setInstallTime(installTime);
//                    if (sensorCoordinateX != null && !sensorCoordinateX.equals("")){
//                        kyLaneBmwy.setSensorCoordinateX(sensorCoordinateX);
//                    }
//                    if (sensorCoordinateY != null && !sensorCoordinateY.equals("")){
//                        kyLaneBmwy.setSensorCoordinateY(sensorCoordinateY);
//                    }
//                    if (sensorCoordinateZ != null && !sensorCoordinateZ.equals("")){
//                        kyLaneBmwy.setSensorCoordinateZ(sensorCoordinateZ);
//                    }
//                    kyLaneBmwy.setSensorCoordinateY(sensorCoordinateY);
//                    kyLaneBmwy.setSensorCoordinateZ(sensorCoordinateZ);
//                    kyLaneBmwy.setReceptionTime(DateUtils.getNowDate());
//
//                    mapper.getKyLaneBmwyService().insertKyLaneBmwy(kyLaneBmwy);
//                    log.info("cost:" + (System.currentTimeMillis() - start));
//
//                    count++;
//                }
//            } catch (Exception e) {
//                log.warn("", e);
//                log.warn("analyze_fail:[{}]", line);
//            }
//        }
//        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
//        fileInfo.setAnalyzed(true);
//    }

    //顶板离层测点基本信 息数据项说明
    private void analyzeDblcFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.pressure.model.FileDto>>) this::analyzeKyDblc).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeKyDblc(final List<FileDto> fileInfos) {
        analyze("DBLC",fileInfos,this::analyzeKyDblc);
    }

    private void analyzeKyDblc(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");
        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);

                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");

                    if (data.length < 11) {
                        log.info("data_invalid: [{}]", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String measurementPointCode = getDatum(data, 0);
                    String monitoringArea = getDatum(data, 1);
                    String sensorType = getSensorType(getDatum(data, 2));
                    String laneName = getDatum(data, 3);
                    String sensorLocation = getDatum(data, 4);
                    Date installTime = new SimpleDateFormat("yyyy-MM-dd").parse(getDatum(data, 5));
                    BigDecimal sensorCoordinateX = getDecimal(data, 6);
                    BigDecimal sensorCoordinateY = getDecimal(data, 7);
                    BigDecimal sensorCoordinateZ = getDecimal(data, 8);
                    BigDecimal sjdInitialInstallDepth = getDecimal(data, 9);
                    BigDecimal qjdInitialInstallDepth = getDecimal(data, 10);


                    KyLaneDblc kyLaneDblc = new KyLaneDblc();
                    kyLaneDblc.setMeasurementPointCode(measurementPointCode);
                    kyLaneDblc.setMonitoringArea(monitoringArea);
                    kyLaneDblc.setSensorType(sensorType);
                    kyLaneDblc.setLaneName(laneName);
                    kyLaneDblc.setSensorLocation(sensorLocation);
                    kyLaneDblc.setInstallTime(installTime);
                    if (sensorCoordinateX != null && !sensorCoordinateX.equals("")){
                        kyLaneDblc.setSensorCoordinateX(sensorCoordinateX);
                    }
                    if (sensorCoordinateY != null && !sensorCoordinateY.equals("")){
                        kyLaneDblc.setSensorCoordinateY(sensorCoordinateY);
                    }
                    if (sensorCoordinateZ != null && !sensorCoordinateZ.equals("")){
                        kyLaneDblc.setSensorCoordinateZ(sensorCoordinateZ);
                    }
                    kyLaneDblc.setSjdInitialInstallDepth(sjdInitialInstallDepth);
                    kyLaneDblc.setQjdInitialInstallDepth(qjdInitialInstallDepth);
                    kyLaneDblc.setReceptionTime(DateUtils.getNowDate());
                    KyLaneDblc kyLaneDblcDb = mapper.getKyLaneDblcService().selectKyLaneDblcByMeasurementPointCode(kyLaneDblc.getMeasurementPointCode());
                    if (kyLaneDblcDb != null){
                        kyLaneDblc.setLaneDblcId(kyLaneDblcDb.getLaneDblcId());
                        mapper.getKyLaneDblcService().updateKyLaneDblc(kyLaneDblc);
                    }else {
                        kyLaneDblc.setLaneDblcId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getKyLaneDblcService().insertKyLaneDblc(kyLaneDblc);
                    }
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    //描杆(索)应力测点 基本信息数据项说明
    private void analyzeMgylFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.pressure.model.FileDto>>) this::analyzeKyMgyl).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeKyMgyl(final List<FileDto> fileInfos) {
        analyze("MGYL",fileInfos,this::analyzeKyMgyl);
    }

    private void analyzeKyMgyl(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");
        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);

                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    if (data.length < 9) {
                        log.info("data_invalid: [{}]", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String measurementPointCode = getDatum(data, 0);
                    String monitoringArea = getDatum(data, 1);
                    String sensorType = getSensorType(getDatum(data, 2));
                    String sensorLocation = getDatum(data, 3);
                    Date installTime = new SimpleDateFormat("yyyy-MM-dd").parse(getDatum(data, 4));
                    BigDecimal sensorCoordinateX = getDecimal(data, 5);
                    BigDecimal sensorCoordinateY = getDecimal(data, 6);
                    BigDecimal sensorCoordinateZ = getDecimal(data, 7);
                    BigDecimal mgBreakingValue = getDecimal(data, 8);


                    KyLaneMgyl kyLaneMgyl = new KyLaneMgyl();
                    kyLaneMgyl.setMeasurementPointCode(measurementPointCode);
                    kyLaneMgyl.setMonitoringArea(monitoringArea);
                    kyLaneMgyl.setSensorType(sensorType);
                    kyLaneMgyl.setSensorLocation(sensorLocation);
                    kyLaneMgyl.setInstallTime(installTime);
                    kyLaneMgyl.setSensorCoordinateX(sensorCoordinateX);
                    kyLaneMgyl.setSensorCoordinateY(sensorCoordinateY);
                    kyLaneMgyl.setSensorCoordinateZ(sensorCoordinateZ);
                    kyLaneMgyl.setMgBreakingValue(mgBreakingValue);
                    kyLaneMgyl.setReceptionTime(DateUtils.getNowDate());
                    KyLaneMgyl kyLaneMgylDb = mapper.getKyLaneMgylService().selectKyLaneMgylByMeasurementPointCode(kyLaneMgyl.getMeasurementPointCode());
                    if (kyLaneMgylDb != null){
                        kyLaneMgyl.setLaneMgylId(kyLaneMgylDb.getLaneMgylId());
                        mapper.getKyLaneMgylService().updateKyLaneMgyl(kyLaneMgyl);
                    }else {
                        kyLaneMgyl.setLaneMgylId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getKyLaneMgylService().insertKyLaneMgyl(kyLaneMgyl);
                    }

                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    //钻 孔应力测 点 基本信 息数据项说明
//    private void analyzeZkylFile(List<FileDto> FileDtos) {
//        List<FileDto> FileDto = FileDtos.stream()
//                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
//                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
//                .collect(Collectors.toList());
//
//        Stream.of((Consumer<List<com.ruoyi.collect.pressure.model.FileDto>>) this::analyzeKyZkyl).parallel().forEach(a -> tryAnalyze(a, FileDto));
//    }
//
//    protected void analyzeKyZkyl(final List<FileDto> fileInfos) {
//        analyze("ZKYL",fileInfos,this::analyzeKyZkyl);
//    }
//
//    private void analyzeKyZkyl(final List<String> matches, final String content, FileDto fileInfo) {
//        long begin = System.currentTimeMillis();
//        int count = 0;
//        String[] lines = content.split("\\|\\|");
//        for (String line : lines) {
//            try {
//                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
//                if (parts.length < 2) {
//                    // 如果字段数量不足，跳过该行
//                    log.warn("Invalid line: {}", line);
//                    continue;
//                }
//                for (int i = 1; i < parts.length; i++) {
//                    // 第一个部分处理
//                    String[] mines = parts[0].split(";");
//                    String mineCode = getDatum(mines, 0);
//
//                    // 第二个部分使用 ';' 分割
//                    String[] data = parts[i].split(";");
//
//                    if (data.length < 11) {
//                        log.info("data_invalid: [{}]", line);
//                        continue;
//                    }
//                    long start = System.currentTimeMillis();
//                    String measurementPointCode = getDatum(data, 0);
//                    String monitoringArea = getDatum(data, 1);
//                    String sensorType = getSensorType(getDatum(data, 2));
//                    String sensorLocation = getDatum(data, 3);
//                    BigDecimal stressMeterInstallDepth = getDecimal(data, 4);
//                    Date installTime = new SimpleDateFormat("yyyy-MM-dd").parse(getDatum(data, 5));
//                    BigDecimal stressMeterCoordinateX = getDecimal(data, 6);
//                    BigDecimal stressMeterCoordinateY = getDecimal(data, 7);
//                    BigDecimal stressMeterCoordinateZ = getDecimal(data, 8);
//                    String stressMeterDirecation = getDatum(data, 9);
//                    String initialStress = getDatum(data, 10);
//
//
//                    KyLaneZkyl kyLaneZkyl = new KyLaneZkyl();
//                    kyLaneZkyl.setLaneZkylId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
//                    kyLaneZkyl.setMeasurementPointCode(measurementPointCode);
//                    kyLaneZkyl.setMonitoringArea(monitoringArea);
//                    kyLaneZkyl.setSensorType(sensorType);
//                    kyLaneZkyl.setSensorLocation(sensorLocation);
//                    kyLaneZkyl.setStressMeterInstallDepth(stressMeterInstallDepth);
//                    kyLaneZkyl.setInstallTime(installTime);
//                    kyLaneZkyl.setStressMeterCoordinateX(stressMeterCoordinateX);
//                    kyLaneZkyl.setStressMeterCoordinateY(stressMeterCoordinateY);
//                    kyLaneZkyl.setStressMeterCoordinateZ(stressMeterCoordinateZ);
//                    kyLaneZkyl.setStressMeterDirecation(stressMeterDirecation);
//                    kyLaneZkyl.setInitialStress(initialStress);
//                    kyLaneZkyl.setReceptionTime(DateUtils.getNowDate());
//                    mapper.getKyLaneZkylService().insertKyLaneZkyl(kyLaneZkyl);
//                    log.info("cost:" + (System.currentTimeMillis() - start));
//
//                    count++;
//                }
//            } catch (Exception e) {
//                log.warn("", e);
//                log.warn("analyze_fail:[{}]", line);
//            }
//        }
//        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
//        fileInfo.setAnalyzed(true);
//    }

    //顶板离层测点实时信息数据项说明
    private void analyzeLcssFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.pressure.model.FileDto>>) this::analyzeKyLcss).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeKyLcss(final List<FileDto> fileInfos) {
        analyze("LCSS",fileInfos,this::analyzeKyLcss);
    }

    private void analyzeKyLcss(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");
        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);

                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");

                    if (data.length < 7) {
                        log.info("data_invalid: [{}]", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String measurementPointCode = getDatum(data, 0);
                    String sensorType = getSensorType(getDatum(data, 1));
                    String sensorLocation = getDatum(data, 2);
                    BigDecimal qjdMonitorValue = getDecimal(data, 3);
                    BigDecimal sjdMonitorValue = getDecimal(data, 4);
                    String measurementPointStatus = getMeasurementPointStatus(getDatum(data, 5));
                    Date receptionTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 6));


                    KyLaneDblcReal kyLaneDblcReal = new KyLaneDblcReal();
                    kyLaneDblcReal.setMeasurementPointCode(measurementPointCode);
                    kyLaneDblcReal.setSensorType(sensorType);
                    kyLaneDblcReal.setSensorLocation(sensorLocation);
                    kyLaneDblcReal.setQjdMonitorValue(qjdMonitorValue);
                    kyLaneDblcReal.setSjdMonitorValue(sjdMonitorValue);
                    kyLaneDblcReal.setMeasurementPointStatus(measurementPointStatus);
                    kyLaneDblcReal.setUpdateTime(receptionTime);
                    KyLaneDblcReal lcssDb = mapper.getKyLaneDblcRealService().selectLcssByMeasurementPointCode(measurementPointCode);
                    if (lcssDb != null){
                        kyLaneDblcReal.setKyLaneDblcRealId(lcssDb.getKyLaneDblcRealId());
                        mapper.getKyLaneDblcRealService().updateKyLaneDblcReal(kyLaneDblcReal);
                    }else{
                        kyLaneDblcReal.setKyLaneDblcRealId(String.valueOf(snowflakeIdUtils.nextId()));
                        mapper.getKyLaneDblcRealService().insertKyLaneDblcReal(kyLaneDblcReal);
                    }
                    KyLaneDblcHistory kyLaneDblcHistory = new KyLaneDblcHistory();
                    BeanUtils.copyProperties(kyLaneDblcReal,kyLaneDblcHistory);
                    kyLaneDblcHistory.setKyLaneDblcRealId(String.valueOf(snowflakeIdUtils.nextId()));
                    mapper.getKyLaneDblcHistoryService().insertKyLaneDblcHistory(kyLaneDblcHistory);
                    mapper.getGradedAlarmService().handleAlarmSpecial(sensorLocation,sensorType, String.valueOf(sjdMonitorValue),"深基点");
                    mapper.getGradedAlarmService().handleAlarmSpecial(sensorLocation,sensorType, String.valueOf(qjdMonitorValue),"浅基点");
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    //描 杆（索）应力测点实时信息数据项说明
    private void analyzeMgssFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.pressure.model.FileDto>>) this::analyzeKyMgss).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeKyMgss(final List<FileDto> fileInfos) {
        analyze("MGSS",fileInfos,this::analyzeKyMgss);
    }

    private void analyzeKyMgss(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");
        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);

                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");

                    if (data.length < 6) {
                        log.info("data_invalid: [{}]", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String measurementPointCode = getDatum(data, 0);
                    String sensorType = getSensorType(getDatum(data, 1));
                    String sensorLocation = getDatum(data, 2);
                    BigDecimal monitorValue = getDecimal(data, 3);
                    String measurementPointStatus = getMeasurementPointStatus(getDatum(data, 4));
                    Date receptionTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 5));



                    KyLaneMgylReal kyLaneMgylReal = new KyLaneMgylReal();
                    kyLaneMgylReal.setMeasurementPointCode(measurementPointCode);
                    kyLaneMgylReal.setSensorType(sensorType);
                    kyLaneMgylReal.setSensorLocation(sensorLocation);
                    kyLaneMgylReal.setMonitorValue(monitorValue);
                    kyLaneMgylReal.setMeasurementPointStatus(measurementPointStatus);
                    kyLaneMgylReal.setUpdateTime(receptionTime);
                    KyLaneMgylReal mgssDb = mapper.getKyLaneMgylRealService().selectMgssByMeasurementPointCode(measurementPointCode);
                    if (mgssDb != null){
                        kyLaneMgylReal.setKyLaneMgylRealId(mgssDb.getKyLaneMgylRealId());
                        mapper.getKyLaneMgylRealService().updateKyLaneMgylReal(kyLaneMgylReal);
                    }else{
                        kyLaneMgylReal.setKyLaneMgylRealId(String.valueOf(snowflakeIdUtils.nextId()));
                        mapper.getKyLaneMgylRealService().insertKyLaneMgylReal(kyLaneMgylReal);
                    }
                    KyLaneMgylHistory kyLaneMgylHistory = new KyLaneMgylHistory();
                    BeanUtils.copyProperties(kyLaneMgylReal,kyLaneMgylHistory);
                    kyLaneMgylHistory.setKyLaneMgylRealId(String.valueOf(snowflakeIdUtils.nextId()));
                    mapper.getKyLaneMgylHistoryService().insertKyLaneMgylHistory(kyLaneMgylHistory);
                    if (sensorLocation != "" && sensorLocation != null && sensorType != "" && sensorType != null && monitorValue != null){
                        GradedAlarmDto gradedAlarmDto = mapper.getGradedAlarmService().handleAlarmNormal(sensorLocation, sensorType, String.valueOf(monitorValue));
                    }
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    //顶 板离层测点异常信息数据项说明
    private void analyzeLcycFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.pressure.model.FileDto>>) this::analyzeKyLcyc).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeKyLcyc(final List<FileDto> fileInfos) {
        analyze("LCYC",fileInfos,this::analyzeKyLcyc);
    }

    private void analyzeKyLcyc(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");
        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);

                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");

                    if (data.length < 12) {
                        log.info("data_invalid: [{}]", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String measurementPointCode = getDatum(data, 0);
                    String sensorType = getSensorType(getDatum(data, 1));
                    String sensorLocation = getDatum(data, 2);
                    String abnormalType = getMeasurementPointStatus(getDatum(data, 3));
                    Date abnormalStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 4));
                    Date abnormalEndTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 5));
                    BigDecimal abnormalValueMax = getDecimal(data, 6);
                    Date valueMaxTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 7));
                    BigDecimal abnormalValueMin = getDecimal(data, 8);
                    Date valueMinTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 9));
                    BigDecimal abnormalValueAvg = getDecimal(data, 10);
                    Date receptionTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 11));



                    KyLaneDblcAbnormal kyLaneDblcAbnormal = new KyLaneDblcAbnormal();
                    kyLaneDblcAbnormal.setKyLaneDblcAbnormalId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    kyLaneDblcAbnormal.setMeasurementPointCode(measurementPointCode);
                    kyLaneDblcAbnormal.setSensorType(sensorType);
                    kyLaneDblcAbnormal.setSensorLocation(sensorLocation);
                    kyLaneDblcAbnormal.setAbnormalType(abnormalType);
                    kyLaneDblcAbnormal.setAbnormalStartTime(abnormalStartTime);
                    kyLaneDblcAbnormal.setAbnormalEndTime(abnormalEndTime);
                    kyLaneDblcAbnormal.setAbnormalValueMax(abnormalValueMax);
                    kyLaneDblcAbnormal.setValueMaxTime(valueMaxTime);
                    kyLaneDblcAbnormal.setAbnormalValueMin(abnormalValueMin);
                    kyLaneDblcAbnormal.setValueMinTime(valueMinTime);
                    kyLaneDblcAbnormal.setAbnormalValueAvg(abnormalValueAvg);
                    kyLaneDblcAbnormal.setReceptionTime(receptionTime);
                    mapper.getKyLaneDblcAbnormalService().insertKyLaneDblcAbnormal(kyLaneDblcAbnormal);
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    //错 杆（索）应力测点异常信息数据项说阴
    private void analyzeMgycFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.pressure.model.FileDto>>) this::analyzeKyMgyc).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeKyMgyc(final List<FileDto> fileInfos) {
        analyze("MGYC",fileInfos,this::analyzeKyMgyc);
    }

    private void analyzeKyMgyc(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");
        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);

                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");

                    if (data.length < 12) {
                        log.info("data_invalid: [{}]", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String measurementPointCode = getDatum(data, 0);
                    String sensorType = getSensorType(getDatum(data, 1));
                    String sensorLocation = getDatum(data, 2);
                    String abnormalType = getMeasurementPointStatus(getDatum(data, 3));
                    Date abnormalStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 4));
                    Date abnormalEndTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 5));
                    BigDecimal abnormalValueMax = getDecimal(data, 6);
                    Date valueMaxTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 7));
                    BigDecimal abnormalValueMin = getDecimal(data, 8);
                    Date valueMinTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 9));
                    BigDecimal abnormalValueAvg = getDecimal(data, 10);
                    Date receptionTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDatum(data, 11));



                    KyLaneMgylAbnormal kyLaneMgylAbnormal = new KyLaneMgylAbnormal();
                    kyLaneMgylAbnormal.setKyLaneMgylAbnormalId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    kyLaneMgylAbnormal.setMeasurementPointCode(measurementPointCode);
                    kyLaneMgylAbnormal.setSensorType(sensorType);
                    kyLaneMgylAbnormal.setSensorLocation(sensorLocation);
                    kyLaneMgylAbnormal.setAbnormalType(abnormalType);
                    kyLaneMgylAbnormal.setAbnormalStartTime(abnormalStartTime);
                    kyLaneMgylAbnormal.setAbnormalEndTime(abnormalEndTime);
                    kyLaneMgylAbnormal.setAbnormalValueMax(abnormalValueMax);
                    kyLaneMgylAbnormal.setValueMaxTime(valueMaxTime);
                    kyLaneMgylAbnormal.setAbnormalValueMin(abnormalValueMin);
                    kyLaneMgylAbnormal.setValueMinTime(valueMinTime);
                    kyLaneMgylAbnormal.setAbnormalValueAvg(abnormalValueAvg);
                    kyLaneMgylAbnormal.setReceptionTime(receptionTime);
                    mapper.getKyLaneMgylAbnormalService().insertKyLaneMgylAbnormal(kyLaneMgylAbnormal);
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }


}
